package sword;

/**
 * @Author: 海琳琦
 * @Date: 2022/5/27 13:57
 * https://leetcode.cn/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/
 */
public class Title53I {

    public int search(int[] nums, int target) {
        int times = 0;
        //二分法
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int middle = (left + right) / 2;
            if (nums[middle] < target) {
                left = middle + 1;
            } else if (nums[middle] > target) {
                right = middle - 1;
            }else{
                //左扩展
                times++;
                for (int i = middle - 1; i >= 0; i--) {
                    if (nums[i] == nums[middle]) {
                        times++;
                    }else{
                        break;
                    }
                }
                for (int i = middle + 1; i < nums.length; i++) {
                    if (nums[i] == nums[middle]) {
                        times++;
                    }else{
                        break;
                    }
                }
                break;
            }
        }
        return times;
    }

    public static void main(String[] args) {

    }
}
